<template>
  <div class="app-container">
    <div class="main-layout">
      <!-- 左侧文件树 -->
      <div class="sidebar" v-if="items.length > 0">
        <div class="sidebar-header">
          <a-button type="primary" @click="openAdd">添加文件</a-button>
          <a-popconfirm
            title="确定要返回吗？未保存的更改将被丢弃"
            ok-text="确定"
            cancel-text="取消"
            @confirm="close"
          >
            <a-button>返回</a-button>
          </a-popconfirm>
        </div>

        <d-tree
          style="height: calc(100vh - 66px); overflow-y: auto"
          :items="items"
          @file-selected="onFileSelected"
        />
      </div>

      <!-- 右侧内容显示区 -->
      <div class="content-area">
        <div v-if="selectedFile" class="file-content">
          <!-- 美化后的内容标题栏 -->
          <div class="content-header">
            <div style="display: flex; align-items: center">
              <h3 class="file-name">
                {{ selectedFile.name }}
              </h3>
              <a-tooltip>
                <template #title>帮助文档</template>
                <img
                  src="/icon/help.svg"
                  style="width: 18px; margin-left: 8px; cursor: pointer"
                  @click="openHelp"
                />
              </a-tooltip>
            </div>
            <div style="display: flex; justify-content: flex-end">
              <!-- 使用 a-space 自动处理按钮间距 -->
              <a-space :size="12">
                <!-- 删除按钮 -->
                <a-popconfirm
                  title="确定要删除该文件吗？此操作不可恢复"
                  ok-text="删除"
                  ok-type="danger"
                  cancel-text="取消"
                  @confirm="handleDelete"
                >
                  <a-button type="primary" danger>
                    <!-- 使用 ant-design-vue 内置图标 -->
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                    删除
                  </a-button>
                </a-popconfirm>

                <!-- 重命名按钮 -->
                <a-button type="default" @click="openRename">
                  <template #icon>
                    <EditOutlined />
                  </template>
                  重命名
                </a-button>

                <!-- 保存按钮 -->
                <a-button type="primary" @click="handleSave">
                  <template #icon>
                    <SaveOutlined />
                  </template>
                  保存
                </a-button>
              </a-space>
            </div>
          </div>
          <common-editor
            height="calc(100vh - 90px)"
            @change="inputChange"
            :content="selectedFile.content"
            mode="java"
            placeholder="输入模板内容"
            theme="solarized_dark"
          />
        </div>
        <div v-else class="placeholder">
          <p>请选择一个文件以查看内容</p>
        </div>
      </div>
    </div>
  </div>

  <a-modal
    v-model:open="showAddModal"
    title="添加文件"
    @ok="handleConfirmAdd"
    @cancel="resetAddForm"
    ok-text="确定"
    cancel-text="取消"
    width="520px"
  >
    <a-form ref="addFormRef" :model="addForm" :rules="addFormRules" layout="vertical">
      <a-form-item label="文件路径" name="filePath">
        <a-input
          v-model:value="addForm.filePath"
          placeholder="输入文件路径，用“/”分隔，如：package/service"
        />
      </a-form-item>

      <a-form-item label="文件名称" name="fileName">
        <a-input
          v-model:value="addForm.fileName"
          placeholder="输入文件名称,如：PageUtil.java"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal
    v-model:open="showRenameModal"
    title="文件重命名"
    @ok="handleConfirmRename"
    @cancel="resetRenameForm"
    ok-text="确定"
    cancel-text="取消"
    width="520px"
  >
    <a-form ref="renameFormRef" :model="renameForm" :rules="renameFormRules" layout="vertical">
      <a-form-item label="文件路径" name="filePath">
        <a-input
          v-model:value="renameForm.filePath"
          placeholder="输入文件路径，用“/”分隔，如：package/service"
        />
      </a-form-item>

      <a-form-item label="文件名称" name="fileName">
        <a-input
          v-model:value="renameForm.fileName"
          placeholder="输入文件名称,如：PageUtil.java"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-drawer v-model:open="helpVisible" title="帮助文档" placement="right" width="500px">
    <MarkdownRenderer :source="helpContent" />
  </a-drawer>
</template>

<script setup>
import router from '@/router'
import commonEditor from '@/views/component/common-editor.vue'
import DTree from '@/views/component/d-tree.vue'
import { message } from 'ant-design-vue'
import { onMounted, ref, reactive } from 'vue'
import Http from '@/api/http'
import { DeleteOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons-vue'
import MarkdownRenderer from '@/views/component/MarkdownRenderer.vue'

const templateId = ref(null)
const addFormRef = ref()
const addForm = reactive({ filePath: 'package/', fileName: '' })
const showAddModal = ref(false)

const addFormRules = {
  filePath: [
    { required: true, message: '请输入文件路径', trigger: 'blur' },
    { max: 200, message: '名称不能超过200个字符', trigger: 'blur' }
  ],
  fileName: [
    { required: true, message: '请输入文件名称', trigger: 'blur' },
    { max: 50, message: '名称不能超过50个字符', trigger: 'blur' }
  ]
}

const renameFormRef = ref()
const renameForm = reactive({ filePath: 'package/', fileName: '' })
const showRenameModal = ref(false)

const renameFormRules = {
  filePath: [
    { required: true, message: '请输入文件路径', trigger: 'blur' },
    { max: 200, message: '名称不能超过200个字符', trigger: 'blur' }
  ],
  fileName: [
    { required: true, message: '请输入文件名称', trigger: 'blur' },
    { max: 50, message: '名称不能超过50个字符', trigger: 'blur' }
  ]
}

// 当前选中的文件
const selectedFile = ref(null)
const items = ref([])
const currentFileContent = ref('')
const helpVisible = ref(false)
const helpContent = ref('')

function openHelp() {
  Http.get('/api/document/templateDoc').then((res) => {
    helpContent.value = res.data
    helpVisible.value = true
  })
}

function inputChange(value) {
  currentFileContent.value = value
}

const openAdd = () => {
  showAddModal.value = true
}

const handleConfirmAdd = () => {
  addFormRef.value
    .validate()
    .then(() => {
      Http.post(`/api/templateInfo/saveFile`, {
        ...addForm,
        leaf: true,
        templateId: templateId.value
      })
        .then((res) => {
          if (res.code === 200) {
            message.success('新增成功！')
            resetAddForm()
            getTemplates()
          }
        })
        .catch(() => message.error('新增失败'))
    })
    .catch(() => {})
}

const resetAddForm = () => {
  addFormRef.value?.resetFields()
  addForm.fileName = null
  addForm.filePath = 'package/'
  showAddModal.value = false
}

const openRename = () => {
  renameForm.fileName = selectedFile.value.name
  renameForm.filePath = selectedFile.value.fullPath.replace(selectedFile.value.name, '')
  showRenameModal.value = true
}

const handleConfirmRename = () => {
  renameFormRef.value
    .validate()
    .then(() => {
      Http.put(`/api/templateInfo/renameFile`, {
        ...renameForm,
        id: selectedFile.value.id,
        templateId: templateId.value,
        leaf: true,
        templateId: templateId.value
      })
        .then((res) => {
          if (res.code === 200) {
            message.success('操作成功！')
            showRenameModal.value = false
            getTemplates()
          }
        })
        .catch(() => message.error('重命名失败'))
    })
    .catch(() => {})
}

const resetRenameForm = () => {
  renameFormRef.value?.resetFields()
  renameForm.fileName = null
  renameForm.filePath = 'package/'
  showRenameModal.value = false
}

// 处理文件选中事件
const onFileSelected = (file) => {
  selectedFile.value = file
}

// 定义按钮点击事件处理函数
const handleDelete = () => {
  Http.delete('/api/templateInfo/delFile/' + selectedFile.value.id).then((res) => {
    message.success('删除成功！')
    getTemplates()
    selectedFile.value = null
  })
}

const handleSave = () => {
  selectedFile.value.content = currentFileContent.value
  Http.put('/api/templateInfo/updateFile', {
    id: selectedFile.value.id,
    templateId: templateId.value,
    fileName: selectedFile.value.name,
    filePath: selectedFile.value.fullPath.replace(selectedFile.value.name, ''),
    leaf: true,
    content: selectedFile.value.content
  }).then((res) => {
    if (res.data) {
      message.success('保存成功！')
    }
  })
}

function close() {
  router.push('/code-template')
}

function getTemplates() {
  Http.get('/api/templateInfo/getFiles/' + templateId.value).then((res) => {
    items.value = buildFileTree(res.data)
  })
}

const buildFileTree = (files) => {
  const rootMap = new Map()
  files.forEach((file) => {
    const pathParts = file.key.split('/')
    const filename = pathParts.pop()
    const [baseName, ext] = filename.split('.')
    let current = rootMap
    // 逐级构建路径
    for (const part of pathParts) {
      if (!current.has(part)) {
        current.set(part, {
          childrenMap: new Map(),
          node: {
            id: part,
            name: part,
            type: 'folder',
            expanded: true,
            children: []
          }
        })
      }
      current = current.get(part).childrenMap
    }
    // 添加文件叶子节点
    const fileNode = {
      id: file.id,
      name: filename,
      type: 'file',
      extension: ext,
      content: file.content,
      fullPath: file.key
    }
    current.set(filename, {
      node: fileNode
    })
  })

  // 递归将 Map 结构转换为 children 数组
  const convertToTree = (map) => {
    const result = []
    for (const item of map.values()) {
      const node = item.node
      if (node.type === 'folder') {
        const childrenMap = item.childrenMap
        if (childrenMap && childrenMap.size > 0) {
          node.children = convertToTree(childrenMap)
        }
      }
      result.push(node)
    }
    return result
  }
  return convertToTree(rootMap)
}

onMounted(() => {
  templateId.value = router.currentRoute.value.params.id
  getTemplates()
})
</script>

<style scoped>
.app-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

.main-layout {
  width: 100%;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  background-color: #ffffff;
  border-right: 1px solid #dee2e6;
  overflow-y: auto;
  padding: 6px 12px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 8px 0;
}

.status-indicator {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
  font-weight: 500;
}

.status-indicator.success {
  background-color: #e6f7e6;
  color: #138413;
  border: 1px solid #b2f2b2;
}

.status-indicator .icon {
  margin-right: 6px;
}

.btn-download {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: background-color 0.2s;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
}

.btn-download:hover {
  background-color: #40a9ff;
  box-shadow: 0 4px 8px rgba(24, 144, 255, 0.3);
}

.btn-download:active {
  transform: translateY(1px);
}

/* 右侧内容区 */
.content-area {
  width: calc(100vw - 580px);
  padding: 12px;
  overflow: auto;
  background-color: #ffffff;
}

.file-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 美化内容标题栏 */
.content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.file-name {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.btn-copy {
  background-color: #f0f0f0;
  color: #555;
  border: 1px solid #ddd;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.2s;
}

.btn-copy:hover {
  background-color: #e0dafe;
  color: #715beb;
}

.btn-copy:active {
  transform: translateY(1px);
}

/* 内容文本 */
.content-text {
  font-family: 'Courier New', monospace;
  overflow: auto;
  border-radius: 4px;
}

/* 占位符 */
.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
  font-size: 16px;
}

/* 图标样式 */
.icon {
  flex-shrink: 0;
}
</style>
